var app = angular.module('webapp');

app.service('UserService', ['$http','$q', UserService]);

function UserService($http,$q){
	function handleRequest(method , url , data , headers){
        var defered = $q.defer();
        var config = {
            method : method,
            url : url
        };
        if(headers){
            config.headers = headers;
        }
        if('POST' === method){
            config.data = data;
        }else if('GET' === method){
            config.params = data;
        }

        $http(config).success(function(data){
            defered.resolve(data);
        }).error(function(err){
            defered.reject(err);
        });
        return defered.promise;
    }
    return {
        getPower:function(data){
            return handleRequest('GET','/getPower',data);
        },
        getUserAll:function(data){
            return handleRequest('GET','/getUserAll',data);
        },
        removeUser:function(data){
            return handleRequest('GET','/removeUser',data);
        },
        saveUser:function(data,successFun,errFun){
            var xhr;
            if(window.ActiveXObject){ //如果是IE浏览器    
                xhr=new ActiveXObject("Microsoft.XMLHTTP");    
            }else if(window.XMLHttpRequest){ //非IE浏览器    
                xhr=new XMLHttpRequest();    
            }   
            xhr.open("post","/saveUser");
            xhr.onreadystatechange = function(){
                var b = xhr.responseText;
                if(xhr.readyState == 4 && xhr.status == 200){        
                    if(b){    
                        successFun(b);    
                    }else{    
                        errFun(b);    
                    }           
                }else{
                    errFun(b);
                }  
            };
            xhr.send(data);
        }
    }
}